package com.cxmx.escort.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cxmx.escort.base.BaseController;
import com.cxmx.escort.base.BasePage;
import com.cxmx.escort.base.ResponseFormat;
import com.cxmx.escort.base.Result;
import com.cxmx.escort.common.SnowflakeIdWorker;
import com.cxmx.escort.common.redis.RedisUtils;
import com.cxmx.escort.entity.BedOrder;
import com.cxmx.escort.entity.Top;
import com.cxmx.escort.entity.User;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

/**
 * <p>
 * 充值表 前端控制器
 * </p>
 *
 * @author 陈云轩
 * @since 2019-10-21
 */
@RestController
@RequestMapping("/top")
@Api(value = " 充值", tags = {" 充值操作接口"})
@Validated
@SuppressWarnings("unchecked")
public class TopController extends BaseController {

    @ApiOperation(value = "充值", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", dataType = "String", paramType = "header", required = true),
    })
    @PostMapping
    public Result<Boolean> addTop(@RequestBody Top top, @NotNull(message = "token不可为空") @RequestHeader("token") String token) throws WxPayException {
        User user = userService.getById(getLongTypeUserId(token));
        WxPayUnifiedOrderRequest wxPayUnifiedOrderRequest = new WxPayUnifiedOrderRequest();
//        Double price = top.getPrice().doubleValue() * 100;
//        wxPayUnifiedOrderRequest.setTotalFee(Integer.parseInt(String.valueOf(price.intValue())));
        wxPayUnifiedOrderRequest.setTotalFee(1);
        wxPayUnifiedOrderRequest.setBody("陪护床账号充值");
        String id = String.valueOf(SnowflakeIdWorker.getId());
        wxPayUnifiedOrderRequest.setOutTradeNo(id);
        wxPayUnifiedOrderRequest.setOpenid(user.getOpenId());
        wxPayUnifiedOrderRequest.setTradeType("JSAPI");
        wxPayUnifiedOrderRequest.setSpbillCreateIp("47.105.133.34");
        wxPayUnifiedOrderRequest.setNotifyUrl("https://api.bochenkj.cn/pay/notify/order");
        wxPayUnifiedOrderRequest.setFeeType("CNY");
        wxPayUnifiedOrderRequest.setVersion("1.0");
        top.setUserId(String.valueOf(getUserId(token)));

        top.setId(id);
        top.setDeleteFlag(1);
        boolean e = topService.save(top);
//        if (e) {
//            user.setBalance(user.getBalance().add(top.getPrice()));
//        }
//        userService.updateById(user);
        return ResponseFormat.retParam(200, wxService.createOrder(wxPayUnifiedOrderRequest));
    }

    @ApiOperation(value = "缴纳押金", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", dataType = "String", paramType = "header", required = true),
    })
    @PostMapping("deposit")
    public Result<Boolean> addDepositTop(@NotNull(message = "token不可为空") @RequestHeader("token") String token) throws WxPayException {
        User user = userService.getById(getLongTypeUserId(token));
        String id = String.valueOf(SnowflakeIdWorker.getId());
        WxPayUnifiedOrderRequest wxPayUnifiedOrderRequest = new WxPayUnifiedOrderRequest();
        Double price = 2.0;
        wxPayUnifiedOrderRequest.setTotalFee(Integer.parseInt(String.valueOf(price.intValue())));
        wxPayUnifiedOrderRequest.setBody("陪护床缴纳押金");
        wxPayUnifiedOrderRequest.setOutTradeNo(id);
        wxPayUnifiedOrderRequest.setOpenid(user.getOpenId());
        wxPayUnifiedOrderRequest.setTradeType("JSAPI");
        wxPayUnifiedOrderRequest.setSpbillCreateIp("47.105.133.34");
        wxPayUnifiedOrderRequest.setNotifyUrl("https://api.bochenkj.cn/pay/notify/depositOrder");
        wxPayUnifiedOrderRequest.setFeeType("CNY");
        wxPayUnifiedOrderRequest.setVersion("1.0");
        user.setDepositId(id);
        userService.updateById(user);
        RedisUtils.set("deposit:user:" + id, user.getId());
        return ResponseFormat.retParam(200, wxService.createOrder(wxPayUnifiedOrderRequest));
    }


    @ApiOperation(value = "退还押金", httpMethod = "PUT")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", dataType = "String", paramType = "header", required = true),
    })
    @PutMapping("deposit")
    public Result<Boolean> uppDepositTop(@NotNull(message = "token不可为空") @RequestHeader("token") String token) throws WxPayException {
        User user = userService.getById(getLongTypeUserId(token));
        QueryWrapper<BedOrder> qw = new QueryWrapper<BedOrder>();
        qw.ne("order_status", 3);
        qw.eq("user_id", getLongTypeUserId(token));
        int a = bedOrderService.count(qw);
        if (a > 0) {
            return ResponseFormat.retParam(70010, null);
        }
        if (null == RedisUtils.get("refund:" + user.getId())) {
            WxPayRefundRequest wxPayUnifiedOrderRequest = new WxPayRefundRequest();
            Double price = 1.0;
            wxPayUnifiedOrderRequest.setRefundFee(Integer.parseInt(String.valueOf(price.intValue())));
            wxPayUnifiedOrderRequest.setTotalFee(2);
            wxPayUnifiedOrderRequest.setRefundDesc("退还押金");
            wxPayUnifiedOrderRequest.setOutTradeNo(user.getDepositId());
            wxPayUnifiedOrderRequest.setNotifyUrl("https://api.bochenkj.cn/pay/notify/refund");
            wxPayUnifiedOrderRequest.setRefundFeeType("CNY");
            wxPayUnifiedOrderRequest.setOutRefundNo(user.getDepositId());
            RedisUtils.set("refund:" + user.getId(), "1");
            return ResponseFormat.retParam(200, wxService.refund(wxPayUnifiedOrderRequest));
        } else {
            return ResponseFormat.retParam(70009, null);
        }
    }

    @ApiOperation(value = "充值列表", httpMethod = "GET")
    @GetMapping("/{pageNum}/{pageSize}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", dataType = "String", paramType = "header", required = true),
            @ApiImplicitParam(paramType = "path", dataType = "String", name = "pageNum", value = "分页", required = true),
            @ApiImplicitParam(paramType = "path", dataType = "int", name = "pageSize", value = "每一页条数", required = true),
    })
    public Result<BasePage<Top>> getPageForOne(@NotNull(message = "pageNum不能为空") @Min(value = 1, message = "分页最小为1") @PathVariable("pageNum") Integer pageNum,
                                               @NotNull(message = "pageSize不能为空") @Max(value = 20, message = "每页最大20") @PathVariable("pageSize") Integer pageSize,
                                               @NotNull(message = "token不可为空") @RequestHeader("token") String token

    ) {
        QueryWrapper<Top> qw = new QueryWrapper<Top>();
        qw.eq("user_id", getLongTypeUserId(token));
        qw.orderByDesc("create_time");
        Page<Top> page = new Page<>(pageNum, pageSize);
        IPage<Top> roleDOList = topService.page(page, qw);
        return ResponseFormat.retParam(200, roleDOList);
    }

//    @ApiOperation(value = "充值总数", httpMethod = "GET")
//    @GetMapping("count")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "token", value = "用户token", dataType = "String", paramType = "header", required = true),
//    })
//    public Result<BigDecimal> getPageForOne(@NotNull(message = "token不可为空") @RequestHeader("token") String token
//
//    ) {
//        List<Top> roleDOList = topService.list(new QueryWrapper<Top>().eq("user_id", getLongTypeUserId(token)));
//        double count = 0.0;
//        for (Top top : roleDOList) {
//            count += top.getPrice().doubleValue();
//        }
//        return ResponseFormat.retParam(200, count);
//    }
}

